import React from 'react'
import {Form, Modal, Input, Select, Tree, Button} from 'antd';
// import OverflowScrolling from 'react-overflow-scrolling';
import API from "../../axios/api";
import { func } from 'prop-types';

const { TreeNode } = Tree;

class SetPermFrom extends React.Component {
    constructor(props){
        super(props)
        this.state = {
            expandedKeys: [],
            autoExpandParent: true,
            checkedKeys: [],
            selectedKeys: [],
            treeData: [],
            checkedKeysResult:[],
            haschildlist:[]
        };
        this.handleSubmit = this.handleSubmit.bind(this)
    }

    onExpand = expandedKeys => {
        console.log('onExpand', expandedKeys);
        // if not set autoExpandParent to false, if children expanded, parent can not collapse.
        // or, you can remove all expanded children keys.
        this.setState({
            expandedKeys,
            autoExpandParent: false,
        });
    };

    onCheck = (checkedKeys,e) => {
        let checkedKeysResult = [...checkedKeys, ...e.halfCheckedKeys];
        this.setState({ 
            checkedKeys,
            checkedKeysResult
        });
    };

    onSelect = (selectedKeys, info) => {
        console.log('onSelect', info);
        this.setState({ selectedKeys });
    };

    renderTreeNodes = data =>
        data.map(item => {
            if (item.data) {
                return (
                    <TreeNode title={item.title} key={item.PermissionId} dataRef={item}>
                        {this.renderTreeNodes(item.data)}
                    </TreeNode>
                );
            }
            return <TreeNode {...item} />;
        });

    handleSubmit = (e) => {
        e && e.preventDefault()
        this.props.form.validateFields((err, values) => {
            if (!err) {
                values.PermissionList = []
                this.state.checkedKeysResult && this.state.checkedKeysResult.map(item => values.PermissionList.push({ "PermissionId": item}) )
                const { onOk } = this.props
                onOk && onOk(values)
                this.props.form.resetFields()
                this.setState({ checkedKeys : [],checkedKeysResult:[]})
            }
        })
    }

    handlerClose = (fn) => {
        this.props.form.resetFields()
        this.setState({ checkedKeys : []})
        fn()
    }

    getRolePermByRoleId =  async (Id) => {
        let haschildlist = []
        this.props.treeData.map(function(item,key){
            if(item.data.length != 0){
                haschildlist.push(item.value)
            }
        })
       
        const parms = {
            Id
        }
        await API.getRolePermissionByRoleId(parms).then((res) => {
            if(res.Code === 200) {
                this.setState({
                    checkedKeysResult:res.Data
                }) 
                let checkedKeys = res.Data
                checkedKeys =  checkedKeys.filter(item=>haschildlist.indexOf(item) == -1)
                this.setState({
                    checkedKeys
                });
            }
        })
    }

    handleSelectChange = async (value) => {
        this.getRolePermByRoleId(value)
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        const {
            modalKey,
            visible,
            title,
            fields,
            onCancel,
            onOk,
            okText,
            roles,
            treeData,
        } = this.props

        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 4 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 },
            },
        }

        return (
            <Modal
                wrapClassName="form"
                key={modalKey}
                visible={visible}
                title={title}
                onCancel={onCancel}
                footer={null}
            >
                <Form onSubmit={this.handleSubmit}  {...formItemLayout} className="login-form">
                    <Form.Item label="角色">
                        {getFieldDecorator('RoleId', {
                            rules: [{ required: true, message: '请选择角色' }],
                        })(
                            <Select
                                onChange={this.handleSelectChange}
                            >
                                {
                                    roles && roles.map(item => {
                                        return (<option value={item.Id}>{item.RoleName}</option>
                                        )
                                    })
                                }
                            </Select>,
                        )}
                    </Form.Item>
                    <Form.Item label="权限分配">
                        <div style={{height: '50vh',overflowY:'scroll'}}>
                            <Tree
                                checkable
                                onExpand={this.onExpand}
                                expandedKeys={this.state.expandedKeys}
                                autoExpandParent={this.state.autoExpandParent}
                                onCheck={this.onCheck}
                                checkedKeys={this.state.checkedKeys}
                                onSelect={this.onSelect}
                                selectedKeys={this.state.selectedKeys}
                                checkable={true}
                            >
                                {this.renderTreeNodes(treeData)}
                            </Tree>
                        </div>
                    </Form.Item>
                    {/*<OverflowScrolling className='overflow-scrolling'>*/}
                        {/*<Form.Item label="权限分配">*/}
                            {/*<Tree*/}
                                {/*checkable*/}
                                {/*onExpand={this.onExpand}*/}
                                {/*expandedKeys={this.state.expandedKeys}*/}
                                {/*autoExpandParent={this.state.autoExpandParent}*/}
                                {/*onCheck={this.onCheck}*/}
                                {/*checkedKeys={this.state.checkedKeys}*/}
                                {/*onSelect={this.onSelect}*/}
                                {/*selectedKeys={this.state.selectedKeys}*/}
                                {/*checkable={true}*/}
                            {/*>*/}
                                {/*{this.renderTreeNodes(treeData)}*/}
                            {/*</Tree>*/}
                        {/*</Form.Item>*/}
                    {/*</OverflowScrolling>*/}
                    <div className="buttons">
                        {this.props.showCancel && <Button onClick={this.onCancel} >取消</Button>}
                        {!this.props.noBtn && <Button type="primary" htmlType="submit">{this.props.okText || '确定'}</Button>}
                    </div>
                </Form>
            </Modal>
        );
    }
}
const SetPermModalForm = Form.create()(SetPermFrom)

export default SetPermModalForm
